import QSelect from '@teld/q-components/Select';
// import { QItem, QItemSection } from '@teld/q-components/Item';
import TItem from 't/basic/item';
import TItemSection from 't/basic/item-section';
import TInput from 't/basic/input';

import {
  commonProps,
} from 't/common/utils';
import {
  computed,
  defineComponent,
  getCurrentInstance,
  nextTick,
  onMounted,
  reactive,
  ref,
  toRef,
  watch,
} from 'vue';

import _, { forIn } from 'lodash';

import {
  date,
  debounce,
  dom,
  setCssVar,
  useQuasar,
  scroll,
} from '@teld/q-components';

import {
  useClipProps,
  useClipItem,
} from 't/bussiness/quick-filter/use-quick-filter';

import label from 't/basic/label';
import TIcon from 't/basic/icon';
export default defineComponent({
  props: {
    ...commonProps,
    ...useClipProps,
    caseSensitive: { type: Boolean, default: false },
    optionsPosition: {
      type: String,
      default: 'top',
    },
  },
  emits: ['filterChanged', 'searchValue', 'loadMore'],

  setup(props, { attrs, emit, expose, slots }) {
    const vm = getCurrentInstance();
    const $q = useQuasar();

    function emitFilterChanged() {
      emit('filterChanged');
    }

    function emitSearchValue() {
      emit('searchValue', { searchValue: searchValue.value, setLoadedAll });
    }

    const modelValue = ref(null);

    const CLEAR_ITEM_VALUE = '_CLEAR_ITEM_';
    const EMPTY_ITEM_VALUE = '_EMPTY_ITEM_';
    const NO_DATA_ITEM_VALUE = '_NO_DATA_';

    const { computedClips } = useClipItem(props);

    watch(
      () => props.clips,
      () => {
        let item = _.filter(computedClips.value, clip => {
          return clip.selected;
        }).map(clip => {
          return clip.value;
        });

        if (props.isMultiple) {
          modelValue.value = item;
        } else {
          modelValue.value = item.length > 0 ? item[0] : null;
        }
      },
      { deep: true },
    );

    const selectOpts = computed(() => {
      if (computedClips.value.length == 0) {
        return [];
      }
      const allItem = {
        label: $q.lang.quickFilter?.all || '全部',
        value: EMPTY_ITEM_VALUE,
      };
      const clearItem = {
        label: $q.lang.quickFilter?.clear || '清除',
        value: CLEAR_ITEM_VALUE,
      };
      let isShowTotalCount = false;
      if (props.enableStatistics && props.showTotalCount) {
        isShowTotalCount = true;
        const sumCount = _.sumBy(computedClips.value, c => c.count);
        if (sumCount) {
          allItem.label = `${allItem.label} ${sumCount}`;
        }
      }
      let showItemCount = 0;
      let returnValue = _.transform(
        computedClips.value,
        (result, item) => {
          result.push({ ...item });
        },
        props.enableAllItem ? [allItem] : [],
      );
      if (false === props.enableAllItem) {
        returnValue.push(clearItem);
      }
      returnValue.forEach(clip => {
        clip.show = true;
        if (searchValue.value) {
          clip.show =
            clip.value == EMPTY_ITEM_VALUE
              ? false
              : props.caseSensitive
                ? clip.label.includes(searchValue.value)
                : clip.label
                    .toLowerCase()
                    .includes(searchValue.value.toLowerCase());
        }
        if (clip.show) {
          showItemCount++;
        }
      });
      // returnValue = returnValue.filter(clip => {
      //   return clip.show;
      // });

      returnValue = returnValue.filter(o => o.show);
      if (returnValue.length == 0 || 0 == showItemCount) {
        returnValue.push({
          label: $q.lang?.select?.noData || '无数据',
          value: NO_DATA_ITEM_VALUE,
        });
      }
      if (props.enableFilter) {
        returnValue.push({});
      }
      return returnValue;
    });

    const clear = () => {
      modelValue.value = null;
      props.clips.forEach(clip => {
        clip.selected = false;
      });
    };

    function itemClickHandler(opt, toggleOption) {
      isChange.value = true;
      if (EMPTY_ITEM_VALUE != opt.value && CLEAR_ITEM_VALUE != opt.value) {
        toggleOption(opt);
        if (props.isMultiple && Object.keys(modelValue.value).length == 0) {
          modelValue.value = null;
        }
      } else {
        clear();
        refSelect.value?.hidePopup();
      }
    }

    function displayText(val) {
      return _.find(selectOpts.value, { value: val })?.label;
    }

    const popupShow = ref(false);
    const isChange = ref(false);

    const refSelect = ref();

    const renderPlaceholder = () => {
      modelValue.value = null;
      return <div class={['placeholder']}>{props.label}</div>;
    };

    const renderSingleItem = () => {
      let text = displayText(modelValue.value);
      return text ? <div class={['item']}>{text}</div> : renderPlaceholder();
    };

    const renderMultipleItem = () => {
      const texts = _.transform(
        modelValue.value,
        (r, val) => {
          let text = displayText(val);
          if (text) {
            r.push(text);
          }
        },
        [],
      );

      return texts.length > 0
        ? texts.map(text => <div class={['item']}>{text}</div>)
        : renderPlaceholder();
    };

    const renderItem = () => {
      return props.isMultiple ? renderMultipleItem() : renderSingleItem();
    };

    const searchValue = ref('');

    const refSelectInput = ref(null);

    const renderTitle=()=>{
      return (
        <div class='quick-filter_select_title-container'>
          <div class='title'>{props.label}</div>
        </div>
      );
    }

    const renderSearch = () => {
      return (
        <div style='position: sticky;top: 0;z-index: 1;'>
          {/* {JSON.stringify(searchValue.value)} */}
          <TInput
            ref={refSelectInput}
            style='padding:0px 8px;;'
            v-model={searchValue.value}
            clearable
            placeholder={
              ($q.lang?.quickFilter?.placeholder?.pleaseEnter || '') +
              props.label
            }
            class='quick-filter_searchbar'
            bg-color='#F0F2F5'
            // dense
            // filled
            onUpdate:modelValue={() => {
              emitSearchValue();
            }}
            standout
            // borderless
            outlined={false}
            bottom-slots
            // onClear={() => { alert(1111)}}
            // placeholder={mappingProps.placeholder}
            // onClick={() => !inDesign && setShowPopup(true)}
            // readonly
            // onFocus={(evt)=> {evt.target.blur(); evt.stopPropagation()} }
          >
            {{
              prepend: () => (
                <TIcon name='icon-fassearch01' style='margin-left: 12px;' />
              ),
            }}
          </TInput>
        </div>
      );
    };

    const renderSearchNoData = () => {
      return (
        <div class={['quick-filter_select_options']}>
          <TItem>
            <TItemSection>{$q.lang?.select?.noData || '无数据'}</TItemSection>
          </TItem>
        </div>
      );
    };

    const isLoadAll = ref(true);
    const pageIndex = ref(1);
    const setLoadedAll = val => {
      if (val == false) {
        pageIndex.value = 1;
      }
      isLoadAll.value = val;
    };

    const renderSearchMore = () => {
      return (
        false === isLoadAll.value && (
          <div class={['quick-filter_select_options']}>
            <TItem>
              <TItemSection>
                <div
                  style='text-align: center;'
                  onClick={() => {
                    if (false === isLoadAll.value) {
                      pageIndex.value += 1;
                      emit('loadMore', {
                        setLoadedAll,
                        // setF(val) {
                        //   if (val == false) {
                        //     pageIndex.value = 1;
                        //   }
                        //   isF.value = val;
                        // },
                        pageIndex: pageIndex.value,
                      });
                    }
                  }}
                >
                  {$q.lang?.quickFilter?.more || '更多'}
                </div>
              </TItemSection>
            </TItem>
          </div>
        )
      );
    };

    return () => {
      let hProps = {
        isMultiple: false,
        label: props.label,
        clips: props.clips,
      };
      return (
        <>
          <QSelect
            ref={refSelect}
            virtual-scroll-slice-size={selectOpts.value.length}
            optionsPosition={props.optionsPosition}
            style='flex:1;'
            class={[
              'tr-select-noborder mobile-select-clip',
              popupShow.value && 'popupShow',
              null == modelValue.value && 'unSelected',
            ]}
            // dropdown-icon={`${TComponents?.IconList?.common ?? 'fas dx-icon'} ${TComponents?.IconList?.arrowDown ?? 'icon-t-arrow-down'} arrow`}
            borderless
            emit-value
            multiple={props.isMultiple}
            map-options
            // clearable
            v-model={modelValue.value}
            onUpdate:modelValue={val => {
              let vals = props.isMultiple ? val : [val];
              props.clips.forEach(clip => {
                clip.selected = vals.includes(clip.value);
              });
            }}
            onPopupShow={() => {
              searchValue.value = '';
              isChange.value = false;
              popupShow.value = true;
              if (props.enableFilter) {
                refSelect.value.refresh(0);
              }
            }}
            onPopupHide={() => {
              searchValue.value = '';
              popupShow.value = false;
              if (isChange.value) {
                emitFilterChanged();
              }
            }}
            options={selectOpts.value}
          >
            {{
              option({ index, itemProps, opt, selected, toggleOption }) {
                return (
                  <>
                    {index == 0 && props.enableFilter && renderSearch()}
                    {index == 0 && props.label && renderTitle()}
                    {NO_DATA_ITEM_VALUE === opt.value
                      ? renderSearchNoData()
                      : opt.show && (
                          <div
                            class={[
                              'quick-filter_select_options',
                              selected && 'selected',
                              CLEAR_ITEM_VALUE === opt.value &&
                                'clearItemContainer',
                            ]}
                            onClick={() => {
                              itemClickHandler(opt, toggleOption);
                            }}
                          >
                            {CLEAR_ITEM_VALUE === opt.value ? (
                              <TItem class='clearItem'>
                                <TItemSection>
                                  <div>{opt.label}</div>
                                </TItemSection>
                              </TItem>
                            ) : (
                              <TItem>
                                <TItemSection>
                                  <div class='quick-filter_option'>
                                    <div class='quick-filter_option_label'>
                                      {opt.label}
                                    </div>
                                    <div class='quick-filter_option_label_right'>
                                      <div class='quick-filter_option_label_right_statistics'>
                                        {props.enableStatistics &&
                                        EMPTY_ITEM_VALUE != opt.value
                                          ? ' ' + opt.count
                                          : ''}
                                      </div>
                                      {props.isMultiple && (
                                        <div class='quick-filter_option_label_right_check'>
                                          {selected && (
                                            <TIcon name='fas dx-icon icon-t-check-fine'></TIcon>
                                          )}
                                        </div>
                                      )}
                                    </div>
                                  </div>
                                </TItemSection>
                                {false && (
                                  <TItemSection side>
                                    <div>
                                      {false && selected && (
                                        <TIcon name='fas dx-icon icon-t-check-fine'></TIcon>
                                      )}
                                    </div>
                                  </TItemSection>
                                )}
                              </TItem>
                            )}
                          </div>
                        )}
                    {index == selectOpts.value.length - 1 && renderSearchMore()}
                  </>
                );
              },
              selected() {
                return (
                  <div
                    class={[
                      'selected',
                      popupShow.value && 'popupShow',
                      null == modelValue.value && 'unSelected',
                    ]}
                  >
                    {null != modelValue.value
                      ? renderItem()
                      : renderPlaceholder()}
                    {false && (
                      <div class={['arrow']}>
                        <TIcon
                          style='font-size:10px'
                          name={`${TComponents?.IconList?.common ?? 'fas dx-icon'} ${TComponents?.IconList?.arrowDown ?? 'icon-t-arrow-down'}`}
                        ></TIcon>
                      </div>
                    )}
                  </div>
                );
              },
            }}
          </QSelect>
        </>
      );
    };
  },
});
